﻿using Newtonsoft.Json;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace BodyFormat
{
    /// <summary>
    /// JSON格式构建
    /// </summary>
    public class Json
    {
        public string build(IEnumerator en)
        {
            StringBuilder sb = new StringBuilder();
            StringWriter sw = new StringWriter(sb);
            using (JsonWriter writer = new JsonTextWriter(sw))
            {
                writer.Formatting = Formatting.Indented;
                writer.WriteStartObject();

                buildNode(en, writer);
                writer.WriteEndObject();
            }
            //正则匹配
            string body = bodyMatch(sb.ToString());
            return "var json =" + body  + ";"; //sb.ToString()
        }

        /// <summary>
        /// 构建
        /// </summary>
        /// <param name="en"></param>
        /// <param name="writer"></param>
        private void buildNode(IEnumerator en, JsonWriter writer)
        {
            while (en.MoveNext())
            {
                //获取转换当前节点数据类型
                DevExpress.XtraTreeList.Nodes.TreeListNode node = (DevExpress.XtraTreeList.Nodes.TreeListNode)en.Current;
                if (node.Nodes.Count > 0)
                {
                    writer.WritePropertyName(node.GetValue("Key").ToString());
                    writer.WriteStartObject();
                    buildNode(node.Nodes.GetEnumerator(), writer);
                    writer.WriteEndObject();
                }
                else
                {
                    writer.WritePropertyName(node.GetValue("Key").ToString() );
                    //writer.WriteValue(@"${" + node.GetValue("Type") + @"}");
                    writer.WriteValue(@"Bodys.get(" + node.GetValue("Key") + @")");
                }
            }
        }

        private string bodyMatch(string body)
        {
            MatchCollection mc = Regex.Matches(body, @"""Bodys.get\(.+\)""");
            foreach (Match item in mc)
            {
                string v = item.Value; 
                string v2 = v;
                v2 =  v2.Replace(@"""","").Replace("(",@"(""").Replace(")",@""")");
                body = body.Replace(v, v2);
            }
            return body;
        }
    
    }
}
